import urllib, hashlib
import random
import requests,sys
import re
import json
import glob

class Transtor():
    def __init__(self):
        pass
    def baiduTranslate(self,text):

        q = text
        fromLang = 'auto'  # 翻译源语言=自动检测
        toLang1 = 'auto'  # 译文语言 = 自动检测

        appid = '20170711000064108'
        salt = random.randint(32768, 65536)
        secretKey = '0y2JkztWWwGFfgivKz2N'  # 密钥

        # 生成sign
        sign = appid + q + str(salt) + secretKey
        # 计算签名sign(对字符串1做md5加密，注意计算md5之前，串1必须为UTF-8编码)
        m1 = hashlib.md5(sign.encode('utf-8'))
        sign = m1.hexdigest()

        # 计算完整请求
        myurl = '/api/trans/vip/translate'
        myurl = myurl + '?appid=' + appid + '&q=' + q + '&from=' + fromLang + '&to=' + toLang1 + '&salt=' + str(
            salt) + '&sign=' + sign
        url = "http://api.fanyi.baidu.com" + myurl

        # 发送请求
        url = url.encode('UTF-8')
        res = requests.get(url)
        # 转换为字典类型
        res = eval(res.text)
        return (res["trans_result"][0]['dst'])

    def googleTranslate(self,text):
        url = 'https://translate.google.cn/_/TranslateWebserverUi/data/batchexecute?rpcids=MkEWBc&f.sid=-2984828793698248690&bl=boq_translate-webserver_20201221.17_p0&hl=zh-CN&soc-app=1&soc-platform=1&soc-device=1&_reqid=5445720&rt=c'
        headers = {
            'origin': 'https://translate.google.cn',
            'referer': 'https://translate.google.cn/',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36',
            'x-client-data': 'CIW2yQEIpbbJAQjEtskBCKmdygEIrMfKAQj2x8oBCPfHygEItMvKAQihz8oBCNzVygEIi5nLAQjBnMsB',
            'Decoded': 'message ClientVariations {repeated int32 variation_id = [3300101, 3300133, 3300164, 3313321, 3318700, 3318774, 3318775, 3319220, 3319713, 3320540, 3329163, 3329601];}',
            'x-same-domain': '1'
        }
        data = {
            'f.req': f'[[["MkEWBc","[[\\"{text}\\",\\"auto\\",\\"zh-CN\\",true],[null]]",null,"generic"]]]'
        }

        res = requests.post(url, headers=headers, data=data).text
        pattern = '\)\]\}\'\s*\d{3,4}\s*\[(.*)\s*'
        part1 = re.findall(pattern, res)
        part1_list = json.loads('[' + part1[0])[0]
        if part1_list[2] is None:
            print(text)
            return text
        content1 = part1_list[2].replace('\n', '')
        part2_list = json.loads(content1)[1][0][0][5:][0]
        s = ''
        for i in part2_list:
            s += i[0]
            # s += i[1][1]
        return s


if __name__ == '__main__':
    pass
